package nl.xvr.server.web;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Logger;

public class WebServerLogger implements Runnable {

	public static final String LOG_FILE_PATH = "D:/Eclipse/os_server/resources/log.txt";

	private ThreadSafeMessageQueue jobs;
	private BufferedWriter writer;

	private WebServerLogger() {
		this.jobs = new ThreadSafeMessageQueue();
		try {
			this.writer = new BufferedWriter(
					new FileWriter(LOG_FILE_PATH, true));
		} catch (IOException e) {
			Logger.getAnonymousLogger().warning(
					"Caught IOException when instantiating file logger: "
							+ e.getMessage());
		}
	}

	/**
	 * Creates a WebServerLogger instance.
	 * 
	 * @return An instance of WebServerLogger.
	 */
	public static WebServerLogger createLogger() {
		WebServerLogger instance = new WebServerLogger();
		new Thread(instance).start();
		return instance;
	}

	public void log(String message) {
		this.jobs.add(message);
	}

	private void logToFile(String message) {
		try {
			this.writer.write(message);
			this.writer.newLine();
			this.writer.flush();
		} catch (IOException e) {
			// Logger.getAnonymousLogger().warning(
			// "Caught IOException when writing to file: "
			// + e.getMessage());
		} finally {
			try {
				this.writer.close();
			} catch (IOException e) {
				Logger.getAnonymousLogger().warning(
						"Caught IOException when closing file logger: "
								+ e.getMessage());
			}
		}
	}

	@Override
	public void run() {
		while (true) {
			if (!this.jobs.isEmpty()) {
				this.logToFile(this.jobs.get());
			}
		}
	}
}
